from rest_framework.response import Response
from rest_framework import status
from d4.d4_models import D4Dic
from d4.d4_serializers import D4DicSerializer
from rest_framework.viewsets import ViewSet
import json


class DicViewSet(ViewSet):
    '''
    CBV下的系统字典管理API
    '''
    def get_list(self, request):
        print("GET 被执行")
        # GET请求
        # 多条记录查询
        dics = D4Dic.objects.all()
        serializer = D4DicSerializer(dics, many=True)
        # serializer.data 转换成 json
        # 可以使用 from rest_framework.renderers import JSONRenderer
        # data = JSONRenderer().render(serializer.data)
        # 可以使用 json.dumps(serializer.data)
        data = json.dumps(serializer.data)
        return Response(json.loads(data))

    def add(self, request):
        print("POST 被执行了")
        # 添加数据请求
        serializer = D4DicSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            print("数据已经被保存")
            print(request.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    def get_object(self, request, pk):
        print("GET 被执行")
        # GET请求
        try:
            dic = D4Dic.objects.get(id=pk)
        except D4Dic.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

        serializer = D4DicSerializer(dic)
        # 返回序列化数据
        return Response(serializer.data)
        # 返回给 html 模板视图，自定义字典
        # return render(request,"dic.html",{"dic":"内容"})
        # 返回给 html 模板视图，查询出来的结果
        # return render(request, "dic.html", serializer.data)

    def update(self, request, pk):
        print("PUT 被执行")
        # 修改数据请
        try:
            dic = D4Dic.objects.get(id=pk)
        except D4Dic.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        serializer = D4DicSerializer(instance=dic, data=request.data)
        if serializer.is_valid():
            serializer.save()
            print("数据被更新了。")
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        print("DELETE被执行")
        # 删除数据请求
        # 单条记录查询
        try:
            dic = D4Dic.objects.get(id=pk)
        except D4Dic.DoesNotExist:
            print("查不到数据")
            return Response(status=status.HTTP_404_NOT_FOUND)
        dic.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
